#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证Token标签页
"""

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QFormLayout, QPushButton, QLabel
)

from src.ui.base_window import BaseWindow


class ValidateTokenTab(BaseWindow):
    """验证Token标签页"""
    
    def __init__(self, client, token_view, main_window=None):
        super().__init__()
        self.client = client
        self.token_view = token_view
        self.main_window = main_window
        
    def build_ui(self) -> QWidget:
        """构建UI界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 验证表单
        form_group = self._create_validation_form()
        layout.addWidget(form_group)
        
        # 验证按钮
        validate_btn = QPushButton("验证 Token")
        validate_btn.clicked.connect(self.on_validate_token)
        validate_btn.setStyleSheet("""
            QPushButton {
                background-color: #FF9800;
                color: white;
                padding: 8px 20px;
                border: none;
                border-radius: 3px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #e68900;
            }
        """)
        layout.addWidget(validate_btn, alignment=Qt.AlignmentFlag.AlignLeft)
        
        # 结果输出区域
        layout.addWidget(QLabel("结果输出："))
        self.result_view = self.create_result_view()
        layout.addWidget(self.result_view)
        
        layout.addStretch()
        return widget
        
    def _create_validation_form(self) -> QWidget:
        """创建验证表单"""
        group = QWidget()
        group.setStyleSheet("""
            QWidget {
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 15px;
                margin: 5px;
            }
        """)
        
        layout = QFormLayout(group)
        
        # Token显示
        layout.addRow("当前 Token：", self.token_view)
        
        return group
        
    def on_validate_token(self):
        """处理Token验证"""
        if not self.client.base_url:
            self.show_warning("未配置站点地址", "请先在'站点设置'中保存 WordPress 站点地址")
            return

        # 确保已登录且有 Token
        token = self.client.get_token()
        if not token:
            self.show_warning("未登录", "请先登录以获取 JWT Token，再进行验证")
            return

        # 切换到验证标签页（如果需要）
        if self.main_window and hasattr(self.main_window, 'tabs'):
            self.main_window.tabs.setCurrentIndex(2)  # "验证 Token"标签页的索引

        # 立即给出界面反馈，避免"没反应"的感觉
        if self.result_view:
            self.result_view.setPlainText("正在验证 Token ...")

        try:
            # 调用验证API
            ok, data = self.client.validate_token(token)
            
            # 显示原始响应数据到结果输出区域
            self.print_result("验证 Token - 原始响应", data)
            
            if ok:
                self.show_message("验证成功", "Token 验证通过！")
            else:
                # 验证失败时显示详细错误信息
                error_msg = "Token 验证失败"
                if "status_code" in data:
                    error_msg += f" (状态码: {data['status_code']})"
                if "suggestion" in data:
                    error_msg += f"\n\n建议: {data['suggestion']}"
                elif "data" in data and data["data"]:
                    error_detail = str(data["data"])
                    if len(error_detail) > 100:
                        error_detail = error_detail[:100] + "..."
                    error_msg += f"\n\n错误详情: {error_detail}"
                self.show_warning("验证失败", error_msg)
                
        except Exception as e:
            error_msg = f"验证过程中发生异常: {str(e)}"
            if self.result_view:
                self.result_view.setPlainText(error_msg)
            self.show_error("验证异常", error_msg)